package com.woniu.rear.comm.core.ribbon;


import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.cloud.nacos.NacosDiscoveryProperties;
import com.alibaba.cloud.nacos.NacosServiceManager;
import com.alibaba.cloud.nacos.ribbon.NacosServer;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.api.naming.pojo.Instance;
import com.alibaba.nacos.client.naming.core.Balancer;
import com.netflix.client.config.IClientConfig;
import com.netflix.loadbalancer.AbstractLoadBalancerRule;
import com.netflix.loadbalancer.BaseLoadBalancer;
import com.netflix.loadbalancer.Server;

import lombok.extern.slf4j.Slf4j;

/**
   *   自定义ribbon规则
 * @author liwei
 *
 */
@Slf4j
public class WeightRule extends AbstractLoadBalancerRule{

	@Autowired
	private NacosDiscoveryProperties nacosDiscoveryProperties;
	
	@Autowired
	private NacosServiceManager nacosServiceManager;
	
	@Override
	public Server choose(Object key) {
		log.info("开始选择节点");
		//获取nacos服务发现注册的核心操作对象
		NamingService maingService = nacosServiceManager.getNamingService(nacosDiscoveryProperties.getNacosProperties());
		//获取需要访问的服务名
		BaseLoadBalancer loadBalancer = (BaseLoadBalancer)getLoadBalancer();
		String name = loadBalancer.getName();
		String groupName = nacosDiscoveryProperties.getGroup();
		String clusterName = nacosDiscoveryProperties.getClusterName();
		
		//通过调用权重算法去选择当前要访问的服务的节点
		try {
			Instance instance = maingService.selectOneHealthyInstance(name, groupName,Arrays.asList(clusterName));
			return new NacosServer(instance);
		} catch (IllegalStateException e) {
			log.error("没有发现同组的:",e);
			List<Instance> instances;
			try {
				instances = maingService.selectInstances(name, true);
				List<Instance> instances1 = new ArrayList<>();
				for(Instance inst : instances) {
					if(inst.getClusterName().equals(clusterName)) {
						instances1.add(inst);
					}
				}
				if(instances1.size() <= 0) instances1 = instances;
				Instance instance = MyBalancer.getHostByWeight(instances1);
				return new NacosServer(instance);
			} catch (NacosException e1) {
				log.error("没有服务:",e1);
			}
		} catch (NacosException e) {
			log.error("nacos异常:",e);
		}
		return null;
	}

	@Override
	public void initWithNiwsConfig(IClientConfig clientConfig) {
	}
	
	static class MyBalancer extends Balancer {
		public static Instance getHostByWeight(List<Instance> hosts) {
			return Balancer.getHostByRandomWeight(hosts);
		}
	}

}
